package com.taoz.mianshiwa.blackfilter;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.yaml.snakeyaml.Yaml;

import java.util.List;
import java.util.Map;

public class BlackIpUtil {

    private static BitMapBloomFilter bloomFilter;
    private static final BitMapBloomFilter EMPTY_BLOOM_FILTER = new BitMapBloomFilter(0);

    // 判断是否是黑名单ip
    public static boolean isBlackIp(String ip) {
        return bloomFilter.contains(ip);
    }

    // 构建ip黑名单
    public static void rebuildBloomFilter(String config) {
        if (StrUtil.isBlank(config)) {
            bloomFilter = EMPTY_BLOOM_FILTER;
            return;
        }

        Yaml yaml = new Yaml();
        Map map = yaml.loadAs(config, Map.class);
        List<String> blackIpList = (List<String>) map.get("blackIpList");
        synchronized (BlackIpUtil.class) {
            if (CollUtil.isEmpty(blackIpList)) {
                bloomFilter = EMPTY_BLOOM_FILTER;
                return;
            }
            BitMapBloomFilter bitMapBloomFilter = new BitMapBloomFilter(5);
            System.out.println(bitMapBloomFilter);
            for (String blackIp : blackIpList) {
                bitMapBloomFilter.add(blackIp);
            }
            bloomFilter = bitMapBloomFilter;
        }
    }
}
